<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      :body-style="{ padding: '0px' }"
      :hide-cancel="isEmpty(form.detailList)"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <ASpin :loading="loading">
        <AScrollbar style="max-height: calc(100vh - 170px); overflow: auto; padding: 20px">
          <AForm v-if="!isEmpty(form.detailList)" ref="formRef" :model="form" auto-label-width>
            <ARow :gutter="10">
              <ACol :span="12">
                <AFormItem
                  field="deliveryDate"
                  label="送货日期"
                  :rules="[{ required: true, message: '请选择送货日期' }]"
                  :validate-trigger="['change', 'input', 'blur']"
                >
                  <ADatePicker v-model="form.deliveryDate" placeholder="送货日期" class="w100" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem
                  field="customerId"
                  label="所属客户"
                  :rules="[{ required: true, message: '请选择所属客户' }]"
                  :validate-trigger="['change', 'input', 'blur']"
                >
                  <ASelect v-model="form.customerId" placeholder="所属客户" allow-search>
                    <AOption
                      v-for="(item, index) in companyList"
                      :key="index"
                      :label="item.customerName"
                      :value="item.customerId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="isInclTax" label="含税">
                  <ASelect v-model="form.isInclTax" placeholder="是否含税" allow-search>
                    <AOption label="是" :value="1"></AOption>
                    <AOption label="否" :value="0"></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="deliveryMethod" label="配送方式">
                  <ASelect v-model="form.deliveryMethod" allow-search placeholder="配送方式">
                    <AOption label="自提" value="自提"></AOption>
                    <AOption label="包送" value="包送"></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="sellersId" label="业务员">
                  <ASelect v-model="form.sellersId" allow-search allow-clear placeholder="业务员">
                    <AOption
                      v-for="(item, index) in employeeList"
                      :key="index"
                      :label="item.employeeName"
                      :value="item.employeeId"
                    ></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="transportCarNo" label="运输车辆">
                  <AInput v-model="form.transportCarNo" placeholder="运输车牌号" />
                </AFormItem>
              </ACol>
              <ACol :span="12">
                <AFormItem field="invoiceStatus" label="开票情况">
                  <ASelect v-model="form.invoiceStatus" allow-search placeholder="开票情况">
                    <AOption label="未开票" value="未开票"></AOption>
                    <AOption label="已提交" value="已提交"></AOption>
                    <AOption label="已开票" value="已开票"></AOption>
                  </ASelect>
                </AFormItem>
              </ACol>
              <ACol :span="24">
                <AFormItem field="attachFiles" label="附件">
                  <upload v-model:attach-files="attachFiles"></upload>
                </AFormItem>
              </ACol>
              <ACol :span="24">
                <AFormItem field="remark" label="备注">
                  <ATextarea v-model="form.remark" placeholder="备注"></ATextarea>
                </AFormItem>
              </ACol>
              <AAlert v-if="!isEmpty(noHasStock)" type="warning" class="erp-mb-6">
                {{
                  `当前选中的销售订单中的${noHasStock.join(',')}没有库存数据请新增相应数据后在创建送货单`
                }}
              </AAlert>
              <ACol :span="24">
                <ACard
                  v-for="(item, index) in form.detailList"
                  :key="index"
                  class="card-container"
                  size="small"
                >
                  <template #extra>
                    <ALink @click="editProduct('add')">增加产品</ALink>
                    <ALink
                      v-if="!item.outboundStatus && form.detailList.length > 1"
                      @click="editProduct('del', index)"
                    >
                      删除产品
                    </ALink>
                  </template>
                  <ARow :gutter="10">
                    <ACol :span="12">
                      <AFormItem
                        :field="`detailList[${index}].materialStockId`"
                        label="产品名称"
                        :rules="[{ required: true, message: '请输入产品名称' }]"
                        :validate-trigger="['change', 'input', 'blur']"
                      >
                        <ASelect
                          v-if="!item.outboundStatus"
                          v-model="item.materialStockId"
                          placeholder="产品名称"
                          allow-search
                          @change="changeEvent('material', item)"
                        >
                          <AOption
                            v-for="(stockItem, index) in stockList"
                            :key="index"
                            :label="stockItem.materialName"
                            :value="stockItem.materialStockId"
                          >
                            <div class="w100 erp-row-center-between">
                              <div>{{ stockItem.materialName }}</div>
                              <ATag v-if="stockItem.spec" color="blue">
                                {{ stockItem.spec }}
                              </ATag>
                            </div>
                          </AOption>
                        </ASelect>
                        <div v-else>{{ item.materialName }}</div>
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="spec" label="规格型号">
                        {{ item.spec }}
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="unit" label="单位">
                        {{ item.unit }}
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="qty" label="数量">
                        <AInputNumber
                          v-if="!item.outboundStatus"
                          v-model="item.qty"
                          model-event="input"
                          placeholder="数量"
                          hide-button
                          :precision="0"
                          :step="1"
                          @change="inputEvent('unitPrice', item)"
                        />
                        <div v-else>{{ item.qty }}</div>
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="unitPrice" label="单价">
                        <AInputNumber
                          v-if="!item.outboundStatus"
                          v-model="item.unitPrice"
                          model-event="input"
                          placeholder="单价"
                          hide-button
                          :precision="4"
                          :step="1"
                          @change="inputEvent('unitPrice', item)"
                        />
                        <div v-else>{{ item.unitPrice }}</div>
                      </AFormItem>
                    </ACol>
                    <ACol :span="12">
                      <AFormItem field="amt" label="金额">
                        <div>{{ `¥${formatPrice(item.amt || 0, 4)}` }}</div>
                      </AFormItem>
                    </ACol>
                  </ARow>
                </ACard>
              </ACol>
            </ARow>
          </AForm>
          <div v-else>
            {{
              `当前选中的销售订单中的${noHasStock.join(',')}没有库存数据请新增相应数据后在创建送货单`
            }}
          </div>
        </AScrollbar>
      </ASpin>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { CustomerResItem, getCustomerAllList } from '@renderer/api/company'
import { DeliveryReq, editDelivery } from '@renderer/api/logisticsDep'
import { formatPrice } from '@renderer/utils/mixins'
import { getStockAllList, StockResItem } from '@renderer/api/warehouseManage'
import { deleteNullObject } from '@renderer/utils/data-processing'
import { differenceBy, isEmpty } from 'lodash-es'
import upload from '@renderer/components/upload/index.vue'
import { useMenuState } from '@renderer/store'
import { EmployeeResItem, getEmployeeAllList } from '@renderer/api/employee'
import { FileListType, getArrayItemType } from '@renderer/types/global'
import { batchDelUploadFile } from '@renderer/api/common'
import { decimalRound } from '@renderer/utils/mixins'
import { SaleResItemHandle } from '@renderer/api/salesDep'

interface Props {
  [key: string]: any
  checkData?: SaleResItemHandle[]
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return []
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const attachFiles = ref<FileListType[]>([])
const form = ref<DeliveryReq>({
  customerId: '',
  customerName: '',
  deliveryDate: '',
  isInclTax: 0,
  transportCarNo: '',
  invoiceStatus: '',
  remark: '',
  detailList: [],
  fileList: [],
  deliveryMethod: '',
  sellersId: '',
  sellersName: ''
})
const companyList = ref<CustomerResItem[]>([])
const stockList = ref<StockResItem[]>([])
const menuParam = useMenuState()
const employeeList = ref<EmployeeResItem[]>([])
const noHasStock = ref<string[]>([])
const loading = ref(false)

// 获取员工列表
const getEmployee = () => {
  getEmployeeAllList({}).then((res) => {
    employeeList.value = res.data.list
  })
}
// 获取产品列表
const getStockList = async () => {
  const res = await getStockAllList({ materialName: '' })
  stockList.value = res.data.list
  const temp = props.checkData.flatMap((item) => item.detailList)
  noHasStock.value = []
  form.value.detailList = []
  for (const item of temp) {
    const ishas = stockList.value.find(
      (stockItem) =>
        stockItem.materialName === item.productName && stockItem.spec === item.specModel
    )
    if (ishas) {
      form.value.detailList.push({
        deliveryOrderDetailId: '',
        deliveryOrderId: '',
        deliveryOrderCode: '',
        materialStockId: ishas.materialStockId!,
        qty: item.qty,
        unitPrice: item.unitPrice!,
        amt: item.amt!,
        unit: ishas.unit!,
        materialName: ishas.materialName!,
        spec: ishas.spec!,
        materialCode: ishas.materialCode!,
        materialDesc: ishas.materialDesc!,
        fluteType: ishas.fluteType!,
        crimpLine: ishas.crimpLine!,
        outboundStatus: 0,
        remark: '',
        orderCode: ''
      })
    } else {
      noHasStock.value.push(item.productName!)
    }
  }
}

// 获取客户列表
const getCompanyList = () => {
  getCustomerAllList({
    customerName: '',
    taxNo: '',
    contactName: ''
  }).then((res) => {
    companyList.value = res.data.list
  })
}

// 弹窗事件
const modalEvent = async (type: string) => {
  loading.value = true
  switch (type) {
    case 'ok':
      if (isEmpty(form.value.detailList)) {
        modalEvent('cancel')
        return
      }
      formRef.value?.validate(async (errors: any) => {
        if (!errors) {
          const delFile = differenceBy(form.value.fileList, attachFiles.value)
          const delFileIds = delFile.map((item) => item.fileId)
          form.value.fileList = attachFiles.value
          // 新增
          if ((attrs.title as string).includes('新增')) {
            form.value.deliveryOrderId = undefined
          }
          if (!isEmpty(delFileIds)) {
            await batchDelUploadFile({ fileIdList: delFileIds })
          }
          editDelivery(deleteNullObject(form.value)).then(() => {
            Message.success('新增成功')
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value?.resetFields()
      form.value = {
        customerId: '',
        customerName: '',
        deliveryDate: '',
        isInclTax: 0,
        sellersName: '',
        sellersId: '',
        transportCarNo: '',
        invoiceStatus: '',
        remark: '',
        detailList: [],
        fileList: [],
        deliveryMethod: ''
      }
      emit('update:visible', false)
      break
    case 'open':
      {
        menuParam.switchEditStatus(true)
        getCompanyList()
        await getStockList()
        getEmployee()
        const temp = props.checkData[0]
        form.value.customerId = temp.customerId
        form.value.customerName = temp.customerName
        form.value.isInclTax = temp.isInclTax
        form.value.deliveryMethod = temp.deliveryMethod
        loading.value = false
      }
      break
    case 'cancel':
      formRef.value?.resetFields()
      form.value = {
        customerId: '',
        customerName: '',
        deliveryDate: '',
        isInclTax: 0,
        transportCarNo: '',
        invoiceStatus: '',
        remark: '',
        detailList: [],
        fileList: [],
        deliveryMethod: '',
        sellersId: '',
        sellersName: ''
      }
      emit('update:visible', false)
      menuParam.switchEditStatus(false)
      break
    default:
      break
  }
}

const editProduct = (type: 'add' | 'del', index?: number) => {
  switch (type) {
    case 'add':
      form.value.detailList.push({
        deliveryOrderDetailId: '',
        deliveryOrderId: '',
        deliveryOrderCode: '',
        materialStockId: '',
        qty: 0,
        unitPrice: 0,
        amt: 0,
        spec: '',
        unit: '',
        materialName: '',
        materialCode: '',
        materialDesc: '',
        fluteType: '',
        crimpLine: '',
        outboundStatus: 0,
        remark: '',
        orderCode: ''
      })
      break
    case 'del':
      form.value.detailList.splice(index!, 1)
      break

    default:
      break
  }
}

const inputEvent = (
  type: 'qty' | 'unitPrice',
  paramsItem: getArrayItemType<DeliveryReq['detailList']>
) => {
  switch (type) {
    case 'qty':
      paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      break
    case 'unitPrice':
      paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      break
    default:
      break
  }
}

const changeEvent = (type: string, detailInfo: getArrayItemType<DeliveryReq['detailList']>) => {
  switch (type) {
    case 'material':
      {
        const temp = stockList.value.find(
          (item) => item.materialStockId === detailInfo.materialStockId
        )
        if (temp) {
          detailInfo.spec = temp.spec!
          detailInfo.unit = temp.unit!
        }
      }
      break

    default:
      break
  }
}
</script>
<style scoped>
.card-container {
  margin-bottom: 10px;
}

:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
